package com.hzjh.h5mall.model.register

import androidx.lifecycle.MutableLiveData
import com.hzjh.base.ext.data.UserConfigs
import com.hzjh.base.ext.frame.JHBaseVM
import com.hzjh.base.ext.route.RouteUrl
import com.hzjh.base.http.toParams
import com.hzjh.base.http.toVersionParams
import com.hzjh.base.router.ext.navigationTo
import com.hzjh.h5mall.bean.register.MnemonicWordBean
import com.hzjh.h5mall.http.MallApi
import java.util.Random

class RegisterVM : JHBaseVM() {
    //助记词列表
    var mnemonicList:MutableLiveData<ArrayList<MnemonicWordBean>> = MutableLiveData(ArrayList())
    //助记词验证成功
    var mnemonicSuccess:MutableLiveData<Boolean> = MutableLiveData(false)

    //获取验证码
    fun reqEmailCaptcha(email:String) {
        makeCall {
            onRequest {
                MallApi.create().reqEmailCaptcha(email.toParams())
            }

            onSuccess {

            }

        }
    }
    //注册邮箱
    fun reqEmailRegister(email:String,captcha:String,password:String) {
        val params = HashMap<Any, Any>()
        params["email"] = email
        params["captcha"] = captcha
        params["password"] = password
        makeCall {
            onRequest {
                MallApi.create().reqEmailRegister(params.toVersionParams())
            }
            onSuccess {
                //邮箱接口调用成功
                navigationTo(RouteUrl.MNEMONIC_ACTIVITY){
                    withString(RouteUrl.PARAMS_EMAIL,email)
                }
            }
        }
    }

    //初始化助记词
    fun initMnemonic() {
        for (i in 0..11){
            mnemonicList.value?.add(MnemonicWordBean())
        }
        mnemonicList.postValue(mnemonicList.value)
    }
    //生成助记词
    fun reqCreateMnemonic(email: String){
        val params = HashMap<Any, Any>()
        params["email"] = email
        makeCall{
            onRequest {
                MallApi.create().reqCreateMnemonic(params.toVersionParams())
            }
            onSuccess {
                mnemonicList.value?.clear()
                mnemonicList.value?.addAll(it)
                mnemonicList.postValue(mnemonicList.value)
            }
        }
    }
    //随机生成校验的助记词
    fun randomMnemonic(dataList:ArrayList<MnemonicWordBean>){
        mnemonicList.value?.clear()
        mnemonicList.value?.addAll(dataList)
        for (i in 0..3){
            val random = Random().nextInt(3)+i*3
            mnemonicList.value?.get(random)?.name=""
        }
        mnemonicList.postValue(mnemonicList.value)
    }
    //校验助记词
    fun reqVerifyMetamaskLogin(email: String,key:String){
        val params = HashMap<Any, Any>()
        params["email"] = email
        params["key"] = key
        makeCall {
            onRequest {
                MallApi.create().reqVerifyMetamaskLogin(params.toVersionParams())
            }
            onSuccess {
                //注册成功 token
                UserConfigs.saveUserData(it)
                mnemonicSuccess.value=true
            }
        }

    }
}